package com.payment.ktb.activity.main4;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.activity.MainActivity;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.PhtotUtils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/9/5.
 */

public class RealNameVerificationActivity extends BaseActivity {
    String timestamp = String.valueOf(new Date().getTime());
    File file = new File(Environment.getExternalStorageDirectory(), "realnameauth.png");
    @BindView(R.id.iv_realnameverification_idcard_front)
    ImageView iv_realnameverification_idcard_front;
    @BindView(R.id.iv_realnameverification_idcard_background)
    ImageView iv_realnameverification_idcard_background;
    @BindView(R.id.iv_realnameverification_idcard_halfbodypicture)
    ImageView iv_realnameverification_idcard_halfbodypicture;
    @BindView(R.id.et_realnameverfication_useraccount)
    EditText et_realnameverfication_useraccount;
    @BindView(R.id.et_realnameverfication_usercert)
    EditText et_realnameverfication_usercert;
    @BindView(R.id.tv_realnameverification_status)
    TextView tv_realnameverification_status;
    @BindView(R.id.tv_realnameverification_failreason)
    TextView tv_realnameverification_failreason;
    @BindView(R.id.btn_realnameverification_submit)
    TextView btn_realnameverification_submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_realnameverification);
        initTitle("实名认证");
        ButterKnife.bind(this);
        initDate();
    }

    private void initDate() {

        tv_realnameverification_status.setText(SharedPreferencesUtils.getString(ConstantsUser.userStatusCn));
        et_realnameverfication_useraccount.setText(SharedPreferencesUtils.getString(ConstantsUser.userAccount));
        et_realnameverfication_usercert.setText(SharedPreferencesUtils.getString(ConstantsUser.userCert));

        //身份证正面照
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1))){
            Picasso.with(mContext).load(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1)).error(R.mipmap.id_card_upload).fit().into(iv_realnameverification_idcard_front);
        }
        //身份证反面照
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2))){
            Picasso.with(mContext).load(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2)).error(R.mipmap.id_card_upload).fit().into(iv_realnameverification_idcard_background);
        }
        //手持身份证半身照
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC3))){
            Picasso.with(mContext).load(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC3)).error(R.mipmap.id_card_upload).fit().into(iv_realnameverification_idcard_halfbodypicture);
        }

        getRealNameVerificationInfo();

    }


    @OnClick({R.id.iv_realnameverification_idcard_front,R.id.iv_realnameverification_idcard_background,R.id.iv_realnameverification_idcard_halfbodypicture,
    R.id.iv_realnameverification_idcard_frontexample,R.id.iv_realnameverification_idcard_backgroundexample,R.id.iv_realnameverification_idcard_halfbodypictureexample,
    R.id.btn_realnameverification_submit}
    )
    public void cliceEvent(View view){
        Intent intent = null;

        switch (view.getId()) {

            //身份证正面照
            case R.id.iv_realnameverification_idcard_front:
                PhtotUtils.takePhoto(this, file, 1);
                break;

            //身份证反面照
            case R.id.iv_realnameverification_idcard_background:
                PhtotUtils.takePhoto(this, file, 2);
                break;

            //手持身份证半身照
            case R.id.iv_realnameverification_idcard_halfbodypicture:
                PhtotUtils.takePhoto(this, file, 3);
                break;

            //身份证正面照示例
            case R.id.iv_realnameverification_idcard_frontexample:
                intent = new Intent(mContext, ShowPhotoActivity.class);
                intent.putExtra("phototype", "1_sample");
                startActivity(intent);
                overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
                break;

            //身份证反面照示例
            case R.id.iv_realnameverification_idcard_backgroundexample:
                intent = new Intent(mContext, ShowPhotoActivity.class);
                intent.putExtra("phototype", "2_sample");
                startActivity(intent);
                overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
                break;

            //手持身份证半身照示例
            case R.id.iv_realnameverification_idcard_halfbodypictureexample:
                intent = new Intent(mContext, ShowPhotoActivity.class);
                intent.putExtra("phototype", "4_sample");
                startActivity(intent);
                overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
                break;
            
            //提交
            case R.id.btn_realnameverification_submit:
                if (checkPass()) {
                    submit();
                }
                break;

        }

    }



    private boolean checkPass() {

        if (TextUtils.isEmpty(et_realnameverfication_useraccount.getText().toString())){
            ToastUtils.showToast("请输入姓名！");
            return false;
        }else if (TextUtils.isEmpty(et_realnameverfication_usercert.getText().toString()) || (et_realnameverfication_usercert.getText().toString().trim().length() != 15 && et_realnameverfication_usercert.getText().toString().trim().length() != 18)) {
            ToastUtils.showToast("请输入正确的身份证！");
            return false;
        }
        else if (TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1))) {
            ToastUtils.showToast("请先上传身份证正面照！");
            return false;
        } else if (TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2))) {
            ToastUtils.showToast("请先上传身份证反面照! ");
            return false;
        }else if (TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC3))) {
            ToastUtils.showToast("请先上传手持身份证半身照! ");
            return false;
        }
        return true;
    }


    private void submit() {

        progressDialogUtils.showProgress();

        String userAccount = et_realnameverfication_useraccount.getText().toString();
        String userCert = et_realnameverfication_usercert.getText().toString();
        String pic1 = SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1);
        String pic2 = SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2);
        String pic3 = SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC3);
        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("userAccount",userAccount);
        map.put("userCert",userCert);
        map.put("pic1",pic1);
        map.put("pic2",pic2);
        map.put("pic3",pic3);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserRealInfoAddState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                ToastUtils.showToast("提交申请成功！");
                startActivity(MainActivity.class);
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == 1 && resultCode == RESULT_OK) {

            // 对拍照之后的图片进行压缩。
            Bitmap bitmap = PhtotUtils.compressBySize(file.getPath(),2560, 1440);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
            Bitmap bitmapTemp = BitmapFactory.decodeFile(file.getPath(),opts);
            // 设置好缩放比例后，加载图片进内容；
            opts.inJustDecodeBounds = false;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            while (baos.toByteArray().length / 1024>200) {
                bitmap = null;
                bitmap = BitmapFactory.decodeFile(file.getPath(), opts);
                opts.inSampleSize = opts.inSampleSize + 5;
                baos.reset();//重置baos即清空baos ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
            }

            //显示图片
            iv_realnameverification_idcard_front.setImageBitmap(bitmap);
            final Bitmap b = PhtotUtils.compressImage(bitmap);
            progressDialogUtils.showProgress("正在上传照片...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile(b, "CertFace");
                }
            }).start();

        } else if (requestCode == 2 && resultCode == RESULT_OK) {
            // 对拍照之后的图片进行压缩。
            // 对拍照之后的图片进行压缩。
            Bitmap bitmap = PhtotUtils.compressBySize(file.getPath(),2560, 1440);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
            Bitmap bitmapTemp = BitmapFactory.decodeFile(file.getPath(),opts);
            // 设置好缩放比例后，加载图片进内容；
            opts.inJustDecodeBounds = false;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            while (baos.toByteArray().length / 1024>200) {
                bitmap = null;
                bitmap = BitmapFactory.decodeFile(file.getPath(), opts);
                opts.inSampleSize = opts.inSampleSize + 5;
                baos.reset();//重置baos即清空baos ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
            }

            //显示图片
            iv_realnameverification_idcard_background.setImageBitmap(bitmap);
            final Bitmap b = PhtotUtils.compressImage(bitmap);
            progressDialogUtils.showProgress("正在上传照片...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile(b, "CertBack");
                }
            }).start();
        }  else if (requestCode == 3 && resultCode == RESULT_OK) {

            // 对拍照之后的图片进行压缩。
            Bitmap bitmap = PhtotUtils.compressBySize(file.getPath(),2560, 1440);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
            Bitmap bitmapTemp = BitmapFactory.decodeFile(file.getPath(),opts);
            // 设置好缩放比例后，加载图片进内容；
            opts.inJustDecodeBounds = false;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            while (baos.toByteArray().length / 1024>200) {
                bitmap = null;
                bitmap = BitmapFactory.decodeFile(file.getPath(), opts);
                opts.inSampleSize = opts.inSampleSize + 5;
                baos.reset();//重置baos即清空baos ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
            }

            //显示图片
            iv_realnameverification_idcard_halfbodypicture.setImageBitmap(bitmap);
            final Bitmap b = PhtotUtils.compressImage(bitmap);
            progressDialogUtils.showProgress("正在上传照片...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile(b, "Other");
                }
            }).start();

        }

    }




    /**
     * 上传照片
     */
    private void uploadFile(Bitmap bitmap, final String type) {


        //将图片写到out中
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        String fileBase64 = Base64.encodeToString(out.toByteArray(), 0, out.toByteArray().length, Base64.DEFAULT);
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //将图片的字节流数据加密成base64字符输出
        fileBase64 = "data:image/png;base64," + fileBase64;

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("fileBase64", fileBase64);
        map.put("type", type);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.FileUploadState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                        JSONObject jsonObject = new JSONObject(response);
                        ToastUtils.showToast("照片上传成功！");
                        switch (type) {
                            case "CertFace":
                                SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1, jsonObject.optString("httpPath"));
                                break;
                            case "CertBack":
                                SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2, jsonObject.optString("httpPath"));
                                break;
                            case "Other":
                                SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC3, jsonObject.optString("httpPath"));
                                break;
                        }

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }

    public void getRealNameVerificationInfo() {


        progressDialogUtils.showProgress();

        //构造传输参数
        Map<String, String> map = new HashMap<String,String>();
        map.put("timestamp",timestamp);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserRealInfoState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    //显示审核驳回原因
                    if (TextUtils.isEmpty(jsonObject.optString("showMsg"))) {
                        tv_realnameverification_failreason.setVisibility(View.GONE);
                    } else {
                        if (SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.userStatus).equals("20")){
                            tv_realnameverification_failreason.setTextColor(mContext.getResources().getColor(R.color.green));
                            btn_realnameverification_submit.setVisibility(View.GONE);
                        }
                        tv_realnameverification_failreason.setText(jsonObject.optString("showMsg"));
                    }
                    //是否可以编辑
                    if (!TextUtils.isEmpty(jsonObject.optString("isEdit")) && jsonObject.optString("isEdit").equals("1")) {
                        et_realnameverfication_useraccount.setEnabled(true);
                        et_realnameverfication_usercert.setEnabled(true);
                        iv_realnameverification_idcard_front.setEnabled(true);
                        iv_realnameverification_idcard_background.setEnabled(true);
                        iv_realnameverification_idcard_halfbodypicture.setEnabled(true);
                        btn_realnameverification_submit.setEnabled(true);
                    }else {
                        et_realnameverfication_useraccount.setEnabled(false);
                        et_realnameverfication_usercert.setEnabled(false);
                        iv_realnameverification_idcard_front.setEnabled(false);
                        iv_realnameverification_idcard_background.setEnabled(false);
                        iv_realnameverification_idcard_halfbodypicture.setEnabled(false);
                        btn_realnameverification_submit.setEnabled(false);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });


    }
}
